package com.rockcent.wechat.localController;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.lib.domain.MallWechatMenuConfig;
import com.rockcent.mall.lib.dto.MallWechatMenuConfigDto;
import com.rockcent.mall.lib.dto.MallWechatMenuListDTO;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.MallWechatMenuConfigHelper;
import com.rockcent.wechat.helper.WechatHelper;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import retrofit2.http.Header;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by DK on 16/11/17.
 * 对接M端微信菜单配置
 */
@RestController
@RequestMapping(value = Routes.API_LOCAL_PREFIX)
public class WechatMenuConfigController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WechatMenuConfigController.class);

    @Autowired
    private WechatHelper wechatHelper;

    /**
     * @api {get} /mall/wechat/menu/config M端微信菜单 菜单发布
     * @apiGroup MALL_WECHAT_MENU
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} domain <code>必传参数</code> 域名
     * @apiParam {Map} menuMap <code>必传参数</code> 菜单集
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MENU_CONFIG, method = RequestMethod.POST)
    private JsonResult wechatMenuConfigForMall(HttpServletRequest request, @RequestParam Map<MallWechatMenuConfig, List<MallWechatMenuConfig>> menuMap, @RequestParam String domain) {
        RestDoing doing = jsonResult -> {
            WxMpService wxMpService = wechatHelper.getWxMpService(domain);
            wxMpService.getMenuService().menuDelete();
            WxMenu wxMenu = new WxMenu();
            List<WxMenuButton> buttons = new ArrayList<>();
            menuMap.forEach((mallWechatMenuConfig, mallWechatMenuConfigList) -> {
                WxMenuButton button = new WxMenuButton();
                //父菜单
                button.setKey(mallWechatMenuConfig.getMenuKey());
                button.setName(mallWechatMenuConfig.getName());
                button.setType(mallWechatMenuConfig.getMenuType());

                //子菜单
                List<WxMenuButton> subButtons = new ArrayList<>();
                for (MallWechatMenuConfig wechatMenuConfig : mallWechatMenuConfigList) {
                    WxMenuButton subButton = new WxMenuButton();
                    subButton.setName(wechatMenuConfig.getName());
                    subButton.setType(wechatMenuConfig.getMenuType());
                    subButton.setUrl(wechatMenuConfig.getPageUrl());
                    subButtons.add(subButton);
                }
                button.setSubButtons(subButtons);
                buttons.add(button);
            });
            wxMenu.setButtons(buttons);
            wxMpService.getMenuService().menuCreate(wxMenu);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /mall/wechat/menu/release M端微信菜单发布创建
     * @apiGroup MALL_WECHAT_MENU
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} domain <code>必传参数</code> 域名
     * @apiParam {String} name <code>必传参数</code> 菜单名称
     * @apiParam {String} pageUrl <code>必传参数</code> 菜单地址
     * @apiParam {String} menuType <code>必传参数</code> 菜单类型
     * @apiSuccess {String} errmsg ok表示成功
     * @apiSuccess {String} errcode 返回错误缟码
     * @apiSuccessExample {json} Success-Response:
     * {
     * "errcode":0,
     * "errmsg":"ok"
     * }
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MENU_RELEASE, method = RequestMethod.POST)
    private JsonResult release(HttpServletRequest request, @RequestBody MallWechatMenuConfigDto dto, @RequestHeader String domain) {
        RestDoing doing = jsonResult -> {
            if (dto == null || dto.getMenuList() == null || dto.getMenuList().size() == 0) {
                jsonResult.remind("菜单列表 不能为空",log);
                return;
            }
            WxMpService wxMpService = wechatHelper.getWxMpService(domain);
            wxMpService.getMenuService().menuDelete();
            WxMenu wxMenu = new WxMenu();
            wxMenu = wechatHelper.convertWechatMenu(wxMenu, dto.getMenuList());
            wxMpService.getMenuService().menuCreate(wxMenu);
        };
        return doing.go(request, log);
    }


    /**
     * @param request
     * @param domain
     * @return
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MENU_LIST, method = RequestMethod.GET)
    private JsonResult getWxMenu(HttpServletRequest request, @RequestHeader String domain) {
        log.info("======================>>>>domain:" + domain);
        RestDoing doing = jsonResult -> {
            WxMpService wxMpService = wechatHelper.getWxMpService(domain);
            log.info("======================>>>>wxMpService:" + wxMpService);
            WxMenu wxMenu = wxMpService.getMenuService().menuGet();
            log.info("======================>>>>wxMenu:" + wxMenu);
            List<MallWechatMenuListDTO> menus = new ArrayList<MallWechatMenuListDTO>();//一级菜单
            if (null != wxMenu) {
                List<WxMenuButton> buttons = wxMenu.getButtons();
                log.info("======================>>>>buttons:" + buttons);
                if (null != buttons && buttons.size() > 0) {
                    buttons.forEach(button -> {
                        MallWechatMenuListDTO menu = MallWechatMenuConfigHelper.SINGLETON.chgWxMenuToMenu(button);
                        List<WxMenuButton> subButtons = button.getSubButtons();
                        log.info("======================>>>>subButtons:" + subButtons);
                        if (null != subButtons && subButtons.size() > 0) {
                            List<MallWechatMenuListDTO> subMenus = new ArrayList<>();//二级菜单
                            subButtons.forEach(subButton -> {
                                MallWechatMenuListDTO subMenu = MallWechatMenuConfigHelper.SINGLETON.chgWxMenuToMenu(subButton);
                                subMenus.add(subMenu);
                            });
                            menu.setChildren(subMenus);
                        }
                        menus.add(menu);
                    });
                }
            }

            menus.forEach(menu -> {
                log.info("======================>menu>>" + menu);
            });
            jsonResult.data = menus;

        };
        return doing.go(request, log);
    }

    /**
     * 根据类别分页获取非图文素材列表
     * @param domain 域名
     * @param type 素材的类型，图片（image）、视频（video）、语音 （voice）
     * @param offset 偏移位置 int offset 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param count 返回数量 int count 取值在1到20之间
     * @return
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MATERIAL_FILEBATCHGET, method = RequestMethod.POST)
    private JsonResult file(HttpServletRequest request, @RequestHeader String domain, @RequestParam String type, @RequestParam int offset, @RequestParam int count) {
        log.info("======================>FILEBATCHGET request:{}",domain+", "+type+", "+offset+", "+count);
        RestDoing doing = jsonResult -> {
            WxMpService wxMpService = wechatHelper.getWxMpService(domain);
            WxMpMaterialFileBatchGetResult wxMpMaterialBatchGetResult = wxMpService.getMaterialService().materialFileBatchGet(type,offset,count);
            log.info("======================>wxMpMaterialBatchGetResult:{}",wxMpMaterialBatchGetResult);
            jsonResult.data=wxMpMaterialBatchGetResult;
        };
        return doing.go(request, log);
    }

    /**
     * 根据类别分页获取图文素材列表
     * @param domain 域名
     * @param offset 偏移位置 int offset 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param count 返回数量 int count 取值在1到20之间
     * @return
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MATERIAL_NEWSBATCHGET, method = RequestMethod.POST)
    private JsonResult news(HttpServletRequest request, @RequestHeader String domain, @RequestParam int offset, @RequestParam int count) {
        log.info("======================>NEWSBATCHGET request:{}",domain+", "+offset+", "+count);
        RestDoing doing = jsonResult -> {
            WxMpService wxMpService = wechatHelper.getWxMpService(domain);
            WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResul = wxMpService.getMaterialService().materialNewsBatchGet(offset,count);
            log.info("======================>wxMpMaterialNewsBatchGetResul:{}",wxMpMaterialNewsBatchGetResul);
            jsonResult.data=wxMpMaterialNewsBatchGetResul;
        };
        return doing.go(request, log);
    }

    /**
     * 获取永久素材
     * @param request
     * @param domain 域名
     * @param type 素材的类型
     * @param mediaId 素材ID
     * @return
     */
    @RequestMapping(value = Routes.MALL_WECHAT_MATERIAL_INFO, method = RequestMethod.POST)
    private JsonResult getMaterial(HttpServletRequest request, @RequestHeader String domain, @RequestParam String type, @RequestParam String mediaId) {
        log.info("======================>getMaterial request:{}",domain+", "+type+", "+mediaId);
        RestDoing doing = jsonResult -> {
            WxMpService wxMpService = wechatHelper.getWxMpService(domain);
            WxMpMaterialNews news = wxMpService.getMaterialService().materialNewsInfo(mediaId);
            log.info("======================>getMaterialResult:{}",news);
            jsonResult.data = news;
        };
        return doing.go(request, log);
    }

}
